package com.casic.ops.runner.pipeline.node.deploy;

import com.alibaba.fastjson.JSON;
import com.casic.ops.entity.domain.MachineInfoDO;
import com.casic.ops.entity.dto.pipeline.datastructure.Logger.NodeLogger;
import com.casic.ops.entity.dto.pipeline.datastructure.context.DefaultResult;
import com.casic.ops.entity.dto.pipeline.datastructure.context.Result;
import com.casic.ops.entity.dto.pipeline.datastructure.executecontext.PipelineExecuteContext;
import com.casic.ops.entity.dto.pipeline.datastructure.node.PipelineNodeConfigInfo;
import com.casic.ops.runner.pipeline.node.DeployAbstractExecutableNode;
import com.casic.ops.runner.pipeline.nodeconfiginfo.deploy.HostDeployNodeConfigInfo;
import com.casic.ops.service.api.MachineInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 主机部署执行节点
 * @author cww
 * @date 2022/6/20
 */
@Service
@Slf4j
public class HostDeployExecutableNode extends DeployAbstractExecutableNode {

    @Resource
    private MachineInfoService machineInfoService;

    @Override
    public Result execute(PipelineExecuteContext context,String nodeUuid) {
        int statusCode=-1;
        NodeLogger logger = (NodeLogger) context.getAttributes(nodeUuid+"logger");
        logger.setNodeName("主机部署");
        log.info(getName());
        PipelineNodeConfigInfo nodeInfo = (PipelineNodeConfigInfo)context.getAttributes(nodeUuid);
        DefaultResult defaultResult = new DefaultResult();
        try {
            log.info("attr : {}" + nodeInfo.toString());
            System.out.println("节点信息:" + nodeInfo.getInfo());
            //Json解析生成配置信息对象
            HostDeployNodeConfigInfo hostDeployNodeInfo = JSON.parseObject(nodeInfo.getInfo(), HostDeployNodeConfigInfo.class);
            long[] ids = hostDeployNodeInfo.getMachineIds();
            List<MachineInfoDO> machineInfoDOList = new ArrayList<>();
            for (long id : ids) {
                MachineInfoDO machineInfoDO = machineInfoService.selectById(id);
                machineInfoDOList.add(machineInfoDO);
            }
            //执行部署脚本
            statusCode = deployShell(logger, context, machineInfoDOList, hostDeployNodeInfo.getDeployScript());
        }catch (Exception e){
            String errorMessage="该节点配置信息为空，请先配置该节点信息"+"\r\n";
            ErrorHandle(e,logger,errorMessage);
        }
        if(statusCode==0) {
            log.info("{}节点执行完成", getName());
        }else {
            log.error("{}节点执行失败",getName());
        }
        defaultResult.add("status",statusCode);
        return defaultResult;

    }
    /**
     * 此方法返回的name是和pipeline_node_template里面节点的name是对应的，如果要修改，请同时去数据库里面，把对应的一条数据的name也改成一致的
     * @return
     */
    @Override
    public String getName() {
        return "HOST_DEPLOY";
    }
}
